<template>
  <div>
    <PageTitleSearch
      :title="title"
      :hotelList="hotelList"
      :currentHotel="currentHotel"
      v-model:lastMonth="lastMonth"
      :currentAcc="currentAcc"
      @hotel-change="handleSelectChange"
      @date-change="handleDateSelect"
      @acc-change="handleAccSelect"
    />
    <div class="main-content">
      <a-row style="margin: 15px 0" :gutter="10">
        <a-col :span="8">
          <div class="title-name">收入占比对比<span class="title-unit">（%）</span></div>
        </a-col>
        <a-col :span="8">
          <div class="title-name">平均房价对比<span class="title-unit">（元）</span></div>
        </a-col>
        <a-col :span="8">
          <div class="title-name">已售间夜数占比对比<span class="title-unit">（%）</span></div>
        </a-col>
      </a-row>
      <a-row :gutter="10">
        <a-col :span="8">
          <FlexCard class="flex-height" :loading="loading" :dataList="incomeData">
            <ContrastBar v-if="incomeData.length > 0" :dataList="incomeData" height="250px" />
          </FlexCard>
        </a-col>
        <a-col :span="8">
          <FlexCard class="flex-height" :loading="loading" :dataList="priceData">
            <ContrastBar v-if="priceData.length > 0" :dataList="priceData" height="250px" />
          </FlexCard>
        </a-col>
        <a-col :span="8">
          <FlexCard class="flex-height" :loading="loading" :dataList="roomData">
            <ContrastBar v-if="roomData.length > 0" :dataList="roomData" height="250px" />
          </FlexCard>
        </a-col>
      </a-row>
      <div class="grid-card">
        <FlexCard style="margin: 15px 0">
          <GridTableNew
            :dataList="tableList"
            :columns="dataColumns"
            :loading="loading"
            :summary="summaryData"
            :customRow="this.customRowHandler"
            :main-title="'客房数据'"
            :sub-title="'市场细分'"
          />
        </FlexCard>
      </div>
      <ReportRemarkCard title="说明" :loading="loading" :reportCode="reportCode" :reportName="reportName" />
    </div>
  </div>
</template>
<script>
  import dayjs from 'dayjs';
  import { defHttp } from '/@/utils/http/axios';
  import * as Color from '/@/utils/ColorDefault';
  import * as MathUtil from '/@/utils/MathUtil';
  import * as Constant from '@/utils/Constant';
  import FlexCard from '@/views/applications/ui/FlexCard.vue';
  import ReportRemarkCard from '@/views/applications/ui/ReportRemarkCard.vue';
  import ContrastBar from '@/views/applications/ui/ContrastBar.vue';
  import GridTableNew from '@/views/applications/ui/GridTableNew.vue';
  import PageTitleSearch from '@/views/applications/ui/PageTitleSearch.vue';

  const REPORT_NAME = '酒店月度市场细分（项目）';
  const REPORT_CODE = 'hotel-month-single-market';
  const APIS = {
    month: 'getHotelMonthMarket',
    year: 'getHotelMonthAccMarket',
  };

  export default {
    name: REPORT_NAME,

    components: {
      FlexCard,
      ReportRemarkCard,
      ContrastBar,
      GridTableNew,
      PageTitleSearch,
    },

    data() {
      return {
        title: '客房部分-市场细分',
        reportCode: '',
        reportName: '',
        loading: false,
        competLoading: false,
        tableHigh: { x: '100%', y: 308 },
        lastMonth: dayjs().subtract(1, 'month').format('YYYYMM'),
        hotelList: [],
        remarkTypeList: [],
        accList: [
          { label: '当月', value: 'month' },
          { label: '当年', value: 'year' },
        ],
        currentHotel: {},
        currentAcc: 'month',
        roomData: [],
        priceData: [],
        perData: [],
        incomeData: [],
        rentRateData: [],
        gopRateData: [],
        competData: [],
        tableList: [],
        dataColumns: [
          {
            title: '',
            dataIndex: 'subjectName',
            width: 150,
            align: 'left',
            ellipsis: true,
            fixed: 'left',
            children: [
              {
                title: '客户收入',
                dataIndex: 'subjectName',
                key: 'subjectName',
                width: 150,
                align: 'left',
                ellipsis: true,
                fixed: 'left',
              },
            ],
          },
          {
            dataIndex: 'room',
            align: 'right',
            width: 100,
            children: [
              {
                title: '间夜',
                dataIndex: 'room',
                key: 'room',
                width: 100,
                align: 'right',
                customRender: (val) => MathUtil.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            title: '当月实际',
            dataIndex: 'price',
            align: 'right',
            width: 100,
            children: [
              {
                title: 'ADR',
                dataIndex: 'price',
                key: 'price',
                width: 100,
                align: 'right',
                customRender: (val) => MathUtil.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'income',
            align: 'right',
            width: 100,
            children: [
              {
                title: '收入',
                dataIndex: 'income',
                key: 'income',
                width: 100,
                align: 'right',
                customRender: (val) => MathUtil.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'incomeRate',
            align: 'right',
            width: 100,
            children: [
              {
                title: '占比',
                dataIndex: 'incomeRate',
                key: 'incomeRate',
                width: 100,
                align: 'right',
                customRender: (val) => MathUtil.percent2DFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lRoom',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '间夜',
                dataIndex: 'lRoom',
                key: 'lRoom',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            title: '去年同期',
            dataIndex: 'lPrice',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: 'ADR',
                dataIndex: 'lPrice',
                key: 'lPrice',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.dot2Formatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lIncome',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '收入',
                dataIndex: 'lIncome',
                key: 'lIncome',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.currencyWNFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'lIncomeRate',
            align: 'right',
            className: 'table-header-color',
            width: 100,
            children: [
              {
                title: '占比',
                dataIndex: 'lIncomeRate',
                key: 'lIncomeRate',
                width: 100,
                align: 'right',
                className: 'table-header-color',
                customRender: (val) => MathUtil.percent2DFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'diffRoom',
            align: 'right',
            width: 100,
            children: [
              {
                title: '间夜',
                dataIndex: 'diffRoom',
                key: 'diffRoom',
                width: 100,
                align: 'right',
                customRender: (val) => MathUtil.percent2DFormatter(val.text, 0),
              },
            ],
          },
          {
            title: '差异率',
            dataIndex: 'diffIncome',
            align: 'right',
            width: 100,
            children: [
              {
                title: '收入',
                dataIndex: 'diffIncome',
                key: 'diffIncome',
                width: 100,
                align: 'right',
                customRender: (val) => MathUtil.percent2DFormatter(val.text, 0),
              },
            ],
          },
          {
            dataIndex: 'diffPrice',
            align: 'right',
            width: 100,
            children: [
              {
                title: 'ADR',
                dataIndex: 'diffPrice',
                key: 'diffPrice',
                width: 100,
                align: 'right',
                customRender: (val) => MathUtil.percent2DFormatter(val.text, 0),
              },
            ],
          },
        ],
      };
    },

    created() {
      Promise.all([
        defHttp.get({ url: '/data/hotel/list' }, { isTransformResponse: false }),
        defHttp.post({
          url: '/data/query',
          data: {
            labelCode: 'getHotelMarkettype',
            sqlParams: [],
            pageIndex: 1,
            pageSize: 100,
          },
        }),
      ]).then(([hotelRes, remarkTypeRes]) => {
        if (hotelRes.code === 200 && hotelRes.result.length > 0 && remarkTypeRes.datas.data) {
          const dataList = hotelRes.result;
          this.hotelList = dataList.map((s) => {
            return { label: s.name, value: s.code };
          });
          const currentHotelCode = this.$route.query.hotelCode || localStorage.getItem(Constant.STORAGE_HOTEL_NAME);
          if (currentHotelCode && dataList.filter((d) => d.code === currentHotelCode).length > 0) {
            this.currentHotel = dataList.filter((d) => d.code === currentHotelCode)[0];
          } else {
            this.currentHotel = {
              code: dataList[0].code,
              name: dataList[0].name,
            };
          }
          this.hotelSel = this.currentHotel;
          const accName = this.accList.filter((a) => a.value === this.currentAcc)[0].label;
          this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
          this.reportName = `${REPORT_NAME}-${accName}-${this.currentHotel.name}-${this.lastMonth}`;
          this.dataColumns[0].title = this.currentAcc === 'month' ? '当月' : '年累计';

          this.remarkTypeList = remarkTypeRes.datas.data;
          this.fetchData();
        }
      });
    },

    methods: {
      fetchData() {
        this.loading = true;
        defHttp
          .post({
            url: '/data/query',
            data: {
              labelCode: APIS[this.currentAcc],
              sqlParams: [
                {
                  key: 'code',
                  value: this.currentHotel.code,
                },
                {
                  key: 'month',
                  value: this.lastMonth,
                },
              ],
              pageIndex: 1,
              pageSize: 100,
            },
          })
          .then((res) => {
            if (res.datas && res.datas.data && res.datas.data.length > 0) {
              const dataList = res.datas.data;
              const scodes = this.remarkTypeList.filter((t) => t.type === '散客').map((t) => t.code);
              const tcodes = this.remarkTypeList.filter((t) => t.type === '团队').map((t) => t.code);

              let ssum = dataList
                .filter((d) => scodes.includes(d.subjectCode))
                .reduce(
                  (acc, item) => {
                    acc.room += Number(item.room) || 0;
                    acc.income += Number(item.income) || 0;
                    acc.lRoom += Number(item.lRoom) || 0;
                    acc.lIncome += Number(item.lIncome) || 0;
                    return acc;
                  },
                  { room: 0, income: 0, lRoom: 0, lIncome: 0 }
                );

              let tsum = dataList
                .filter((d) => tcodes.includes(d.subjectCode))
                .reduce(
                  (acc, item) => {
                    acc.room += Number(item.room) || 0;
                    acc.income += Number(item.income) || 0;
                    acc.lRoom += Number(item.lRoom) || 0;
                    acc.lIncome += Number(item.lIncome) || 0;
                    return acc;
                  },
                  { room: 0, income: 0, lRoom: 0, lIncome: 0 }
                );

              const sum = {
                room: tsum.room + ssum.room,
                income: tsum.income + ssum.income,
                lRoom: tsum.lRoom + ssum.lRoom,
                lIncome: tsum.lIncome + ssum.lIncome,
              };

              ssum = this.wrapTableData(
                {
                  ...ssum,
                  subjectCode: 'ssum',
                  subjectName: '散客小计',
                },
                sum
              );
              tsum = this.wrapTableData({ ...tsum, subjectCode: 'tsum', subjectName: '团队小计' }, sum);

              // 更新图表数据
              this.incomeData = this.wrapImageData(ssum, tsum, 'incomeRate', 'lIncomeRate', 'percent2DFormatter|0');
              this.roomData = this.wrapImageData(ssum, tsum, 'roomRate', 'lRoomRate', 'percent2DFormatter|0');
              this.priceData = this.wrapImageData(ssum, tsum, 'price', 'lPrice', 'dot2Formatter|0');

              // 处理表格数据
              const slist = this.remarkTypeList
                .filter((t) => t.type === '散客')
                .map((t) => {
                  const ds = dataList.filter((d) => d.subjectCode === t.code);
                  let d = {};
                  if (ds.length > 0) {
                    d = {
                      ...ds[0],
                    };
                  } else {
                    d = {
                      subjectCode: t.code,
                      subjectName: t.name,
                      room: 0,
                      income: 0,
                      lRoom: 0,
                      lIncome: 0,
                    };
                  }
                  return this.wrapTableData(d, sum);
                });

              const tlist = this.remarkTypeList
                .filter((t) => t.type === '团队')
                .map((t) => {
                  const ds = dataList.filter((d) => d.subjectCode === t.code);
                  let d = {};
                  if (ds.length > 0) {
                    d = {
                      ...ds[0],
                    };
                  } else {
                    d = {
                      subjectCode: t.code,
                      subjectName: t.name,
                      room: 0,
                      income: 0,
                      lRoom: 0,
                      lIncome: 0,
                    };
                  }
                  return this.wrapTableData(d, sum);
                });

              this.tableList = [...slist, ssum, ...tlist, tsum];
            } else {
              this.incomeData = [];
              this.roomData = [];
              this.priceData = [];
              this.tableList = [];
            }
            localStorage.setItem(Constant.STORAGE_HOTEL_NAME, this.currentHotel.code);
            this.loading = false;
          })
          .catch((error) => {
            console.error('Error fetching data:', error);
            this.loading = false;
            this.incomeData = [];
            this.roomData = [];
            this.priceData = [];
            this.tableList = [];
          });
      },
      wrapImageData(data1, data2, field, lfield, formatter) {
        return [
          {
            title: data1.subjectName.replace('小计', ''),
            item: [
              {
                name: '实际',
                value: data1[field],
                formatter,
              },
              {
                name: '去年',
                value: data1[lfield],
                formatter,
              },
            ],
          },
          {
            title: data2.subjectName.replace('小计', ''),
            item: [
              {
                name: '实际',
                value: data2[field],
                formatter,
              },
              {
                name: '去年',
                value: data2[lfield],
                formatter,
              },
            ],
          },
        ];
      },
      wrapTableData(data, sum) {
        return {
          ...data,
          roomRate: MathUtil.safeDivide(data.room, sum.room),
          incomeRate: MathUtil.safeDivide(data.income, sum.income),
          lRoomRate: MathUtil.safeDivide(data.lRoom, sum.lRoom),
          lIncomeRate: MathUtil.safeDivide(data.lIncome, sum.lIncome),
          price: MathUtil.safeDivide(data.income, data.room),
          lPrice: MathUtil.safeDivide(data.lIncome, data.lRoom),
          diffRoom: MathUtil.diff(data.room, data.lRoom),
          diffIncome: MathUtil.diff(data.income, data.lIncome),
          diffPrice: MathUtil.diff(MathUtil.safeDivide(data.income, data.room), MathUtil.safeDivide(data.lIncome, data.lRoom)),
        };
      },
      summaryData() {
        const sum = this.tableList
          .filter((t) => t.subjectCode.includes('sum'))
          .reduce(
            (acc, item) => {
              acc.room += item.room;
              acc.income += item.income;
              acc.lRoom += item.lRoom;
              acc.lIncome += item.lIncome;
              return acc;
            },
            { room: 0, income: 0, lRoom: 0, lIncome: 0 }
          );
        let record = { ...sum, subjectCode: 'sum', subjectName: '酒店总计' };
        record = this.wrapTableData(record, sum);
        this.customRenderData(record, this.dataColumns);
        return [record];
      },
      customRenderData(data, columns) {
        columns.forEach((c) => {
          if (c.customRender) {
            const value = { text: data[c.dataIndex] };
            data[c.dataIndex] = c.customRender(value);
          }
          if (c.children) {
            this.customRenderData(data, c.children);
          }
        });
      },
      customRowHandler(record, index) {
        const style = {};
        // 如果当前行的 key 与存储的 specialRowKey 相同，则添加特殊背景颜色
        if (record.subjectName.includes('总计')) {
          style.backgroundColor = Color.COLOR_LIGHT_BLUE;
        }
        return {
          // 为行添加鼠标移入事件
          onMouseenter: () => {
            console.log(`Mouse entered row with index ${index}`);
          },
          // 为行添加鼠标移出事件
          onMouseleave: () => {
            console.log(`Mouse left row with index ${index}`);
          },
          // 为行添加点击事件
          onClick: () => {
            console.log(`Clicked on row with index ${index}`);
          },
          // 为行添加样式
          style: style,
        };
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
      },
      handleSelectChange(value) {
        this.currentHotel = {
          code: value,
          name: this.hotelList.filter((h) => h.value === value)[0].label,
        };
        const accName = this.accList.filter((a) => a.value === this.currentAcc)[0].label;
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${accName}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
      },
      handleAccSelect(value) {
        const name = this.accList.filter((h) => h.value === value)[0].label;
        this.currentAcc = value;
        this.reportCode = `${REPORT_CODE}-${value}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${name}-${this.currentHotel.name}-${this.lastMonth}`;
        this.dataColumns[0].title = this.currentAcc === 'month' ? '当月' : '年累计';
        this.fetchData();
      },
      handleDataChange(val) {
        this.dateSel = val;
      },
      showFilterPopup() {
        this.filterPopup = true;
        this.dateSel = this.currentDate;
      },
      cancelFilter() {
        this.filterPopup = false;
      },
      confirmFilter() {
        this.currentDate = this.dateSel;
        this.fetchData();
        this.filterPopup = false;
      },
      isMonthDisabled(current) {
        const lastMonth = dayjs().subtract(1, 'month');
        return current.isAfter(lastMonth);
      },
      handleDateSelect() {
        const name = this.accList.filter((h) => h.value === this.currentAcc)[0].label;
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.currentHotel.code}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${name}-${this.currentHotel.name}-${this.lastMonth}`;
        this.fetchData();
      },
    },
  };
</script>

<style lang="less" scoped>
  .main-content {
    // padding: 12px 0;

    &-title {
      &-custom {
        color: #00b578;
      }
    }
  }

  .card-double {
    display: flex;
    margin: 12px 0 12px 0;
    justify-content: space-between;

    &-item {
      flex-basis: 48%;
    }
  }

  .interval-area {
    margin-bottom: 12px;
  }

  .select-title-space {
    width: 200px;
    margin-right: 20px;
  }

  ::v-deep .select-title .van-cell {
    color: hsl(217, 16%, 60%);
    font-size: 0.875rem;
    line-height: 1.25rem;
    padding: unset;
    -webkit-box-pack: end;
    -ms-flex-pack: end;
    justify-content: flex-end;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    position: relative;
    background-color: #112c4d;
  }

  .popup-right {
    width: auto;

    &-content {
      height: 800px;
      width: 318px;

      &-oprate {
        display: flex;
        padding: 16px;
        justify-content: center;

        &-item {
          width: 100%;
          margin-right: 10px;
        }

        &-item:last-child {
          margin-right: 0;
        }
      }
    }
  }

  @media @desktop {
    .row-content {
      display: flex;
    }

    .main-frame-desktop-header {
      padding: 1rem;
      background: #fff;
      overflow: hidden;
    }

    .echarts {
      width: 100%;
      height: 236px;
    }
    .title-wrap {
    }
    .title-name {
      height: 36px;
      background: #ffffff;
      -webkit-box-shadow: 0px 5px 5px 0px rgba(25, 15, 15, 0.07);
      box-shadow: 0px 5px 5px 0px rgba(25, 15, 15, 0.07);
      border-radius: 0.4rem;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      font-weight: 600;
      .title-unit {
        font-weight: 400;
      }
    }

    .flex-height {
      white-space: pre-line;
      height: 268px;
    }
    .card-flex-all {
      flex: 1 1 calc(100% - 10px);
    }
  }

  .full-width-remark {
    width: 100%;
    margin: 10px 0;
  }
  .grid-card {
    min-height: calc(100vh - 500px);
    display: flex; /* 关键属性 */
    flex-direction: column; /* 垂直排列 */
  }
</style>
